package org.duang.core;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;

import org.duang.config.Config;
import org.duang.plugins.Plugins;



/**
 * Application Lifecycle Listener implementation class ContainerListener
 *
 */
@WebListener
public class ContainerListener  implements ServletContextListener {
	
    /**
     * 容器销毁时监听
     */
	public void contextDestroyed(ServletContextEvent sec) {
		Plugins.stop();
	}

	/**
	 * 容器启动时监听
	 */
	public void contextInitialized(ServletContextEvent sec) {	
		ServletContext servletContext = sec.getServletContext();		
//        registerShiroListener(servletContext); 		// 注册shiro Listener
		addServletMapping(servletContext);			//注册映射	
		MVC.init(servletContext);					//框架初始化
	}

	
    private void addServletMapping(ServletContext context) {
        // 用 DefaultServlet 映射所有静态资源
        registerDefaultServlet(context);
        // 用 JspServlet 映射所有 JSP 请求
        registerJspServlet(context);
        
    }

    private void registerDefaultServlet(ServletContext context) {
        ServletRegistration defaultServlet = context.getServletRegistration("default");
        defaultServlet.addMapping("/index.html");
        defaultServlet.addMapping("/favicon.ico");
        defaultServlet.addMapping("/static/*");
    }

    private void registerJspServlet(ServletContext context) {
        ServletRegistration jspServlet = context.getServletRegistration("jsp");
        jspServlet.addMapping("/index.jsp");        
        jspServlet.addMapping(Config.getViewRootPath()+"/*");
    }
    
	@SuppressWarnings("unused")
	private void registerShiroListener(ServletContext context) {
    	// 初始化 SecurityManager
//    	Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//    	org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager)factory.getInstance();
//        SecurityUtils.setSecurityManager(securityManager);
//    	WebEnvironment env = WebUtils.getRequiredWebEnvironment(context);
//    	System.out.println(env);
    	// 注册 Listener
//    	context.addListener("com.fast4j.core.SecurityInitializer");//.addListener(SecurityInitializer.class);  
    	// 注册 Filter
//    	FilterRegistration.Dynamic shiroFilter = context.addFilter("ShiroFilter", ShiroFilter.class);
//    	shiroFilter.addMappingForUrlPatterns(null, false, "/*");
       
    }	
}
